package com.cartoonrabbit.config.security.service;

import com.cartoonrabbit.config.exception.ServiceException;
import com.cartoonrabbit.config.security.pojo.LoginUser;
import com.cartoonrabbit.pojo.User;
import com.cartoonrabbit.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;



@Service
public class UserDetailServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);
    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String openId) throws UsernameNotFoundException {
        //根据用户名查取用户
        User user = userService.getUserInfoByOpenId(openId);
        if (ObjectUtils.isEmpty(user))
        {
            log.info("登录用户：{} 不存在.", openId);
            throw new ServiceException("登录用户：" + openId + " 不存在");
        }

        else if (user.getIsEnable()==0)
        {
            log.info("登录用户：{} 已被停用.", openId);
            throw new ServiceException("对不起，您的账号：" + openId + " 已停用");
        }
        //封装成UserDetails
        LoginUser loginUser = new LoginUser(user);
        return loginUser;
    }
}
